<template>
  <view class="CoffeeMaker">
    <ProgramControl
      :enable-power-off-tips="enablePowerOffTips"
      :show-control-view-forced="isStartupCleaning"
      :share-disabled="isStartupCleaning"
      :control="baseControl"
      :active-program-tips="activeProgramTips"
      :custom-state-getter="customStateGetter"
      :is-hide-adjust-btn="isHideAdjustBtn"
      :height-effect-triggers="[() => isShowBeanBox]"
      @adjust="openAdjustParameter"
    >
      <template #aside-control>
        <AsideControl
          :control="baseControl"
          :role="AsideRoles.Power"
          :overwrites="powerControlOverwrites"
          :prevent="control.store.shouldConfirmShutdown"
          @power-change="onPowerChange"
        />
      </template>
      <template #cover-suffix>
        <view class="bean-box" v-if="isShowBeanBox">
          <view class="bean-font">{{ $t('CoffeeMaker.DetailMiddle.Bean.Title.Text') }}</view>
          <view class="bean-operate" @click="changeBean">
            <view class="bean-left bean" :class="{ active: switchBean }">{{
              $t('CoffeeMaker.DetailMiddle.Bean.Content.Left.Text')
            }}</view>
            <view class="bean-right bean" :class="{ active: !switchBean }">{{
              $t('CoffeeMaker.DetailMiddle.Bean.Content.Right.Text')
            }}</view>
          </view>
        </view>
      </template>
      <template #action-prefix v-if="!isHideAdjustBtn">
        <view class="double-cup" v-if="!isHideAdjustBtn" :class="{ disabled: doubleDisabled }" @click="chooseDouble">
          <view class="double-img-box">
            <image src="/static/ic_selected_radio.png" v-if="isDouble"></image>
            <image src="/static/ic_unselected_radio.png" v-else></image>
          </view>
          <view class="double-cup-font">{{ $t('CoffeeMaker.DetailMiddle.DoubleCup.Text') }}</view>
        </view>
      </template>
      <AdjustParameterModal
        v-model:show="adjustParameterVisible"
        :control="baseControl"
        :active-program-tips="activeProgramTips"
      >
        <template #start-footer>
          <view class="double-cup" v-if="!isHideAdjustBtn" :class="{ disabled: doubleDisabled }" @click="chooseDouble">
            <view class="double-img-box">
              <image src="/static/ic_selected_radio.png" v-if="isDouble"></image>
              <image src="/static/ic_unselected_radio.png" v-else></image>
            </view>
            <view class="double-cup-font">{{ $t('CoffeeMaker.DetailMiddle.DoubleCup.Text') }}</view>
          </view>
        </template>
      </AdjustParameterModal>
      <ShutdownTips v-model:show="showShutdownTips" :control="control" @confirm="confirmShutdown" />
    </ProgramControl>

    <!-- 固件升级成功 -->
    <SuccessAcknowledge v-if="otaHelper" :helper="otaHelper" />

    <Mask :show="isStartupCleaning" type="loading" :title="$t('CoffeeMaker.OnOff.ClearStart.Loading.Text')" />
  </view>
</template>

<script setup lang="ts">
import ProgramControl from '../view/control/programControl.vue'
import AsideControl from '../view/control/components/AsideControl.vue'
import Mask from '@/common/mask.vue'
import AdjustParameterModal from '../view/adjustParameterModal.vue'

import type { BaseController } from '@/controller/BaseAppliance/definition'
import { AsideRoles, useControlState } from '@/controller/BaseAppliance/useControl'
import { useScrollProvider } from '@/utils/composition/useScroll'
// 注意：请勿将onShareAppMessage删除
import { onPageScroll, onShareAppMessage } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import {
  COFFEE_BEAN_CONTAINER_SELECTION,
  COFFEE_BEAN_CONTAINER_SELECTION_LEFT,
  COFFEE_BEAN_CONTAINER_SELECTION_RIGHT,
  COFFEE_FILL_QUNTITY,
  COFFEE_MULTIPLE_BEVERAGES,
  OPERATION_PAUSE_PROGRAM,
  OPERATION_STATES,
} from '@/constants/Command'
import { selectProgram } from '@/api/appliance'
import type { CustomConfigGetter, StateViewConfig } from '../view/stateView.vue'
import type { CoffeeMakerController } from '@/controller/CoffeeMaker/definition'
import { actionDebounce } from '@/utils/mpHelper'
import { useShutdown } from '../view/powerShutdown/useShutdown'
import ShutdownTips from '../view/powerShutdown/shutdownTips.vue'
import SuccessAcknowledge from '../settings/ota/modals/successAcknowledge.vue'
import { useInhouseOtaHelper } from '../view/useOtaHelper'

const props = defineProps<{
  control: CoffeeMakerController.Control
}>()

const control = props.control

const { setScrollTop } = useScrollProvider()
onPageScroll(({ scrollTop }) => setScrollTop(scrollTop))

const baseControl = control as BaseController.Control

const controlState = useControlState(control)
const { isPowerOn } = controlState
const activeProgramKey = computed(() => control.store.currentProgramKey)
const i18n = useI18n()

/**
 * OTA升级
 */
const otaHelper = useInhouseOtaHelper(control)

/**
 * 断电处理
 */
const { powerControlOverwrites, onPowerChange, showShutdownTips, confirmShutdown } = useShutdown(control)

/**
 * 开关机时清洁状态
 */
const isStartupCleaning = computed(() => control.store.isStartupCleaning)
const enablePowerOffTips = computed(() => isStartupCleaning.value && control.store.customizedAllPrograms.length === 0)

/**
 * 选中程序提示
 */
const activeProgramTips = computed(() => {
  const fillQuantity = control.store.detail?.option?.find((item) => {
    return item.key === COFFEE_FILL_QUNTITY
  })
  if (!fillQuantity) return ''
  const suffix = fillQuantity.unit || ''
  return fillQuantity.value + suffix
})

/**
 * 调节参数
 */
const adjustParameterVisible = ref(false)
async function openAdjustParameter() {
  adjustParameterVisible.value = true
}

/**
 * 豆仓
 */
const switchBean = computed(() => (control.store.switchBean === COFFEE_BEAN_CONTAINER_SELECTION_LEFT ? true : false))
const isShowBeanBox = computed(() =>
  control.store.detail?.option?.some((option) => option.key === COFFEE_BEAN_CONTAINER_SELECTION)
)
//切换豆仓
const changeBean = actionDebounce({
  loadingText: i18n.t('APP.Common.Submitting.Text'),
  call: async () => {
    let options = [
      {
        key: COFFEE_BEAN_CONTAINER_SELECTION,
        value: !switchBean.value ? COFFEE_BEAN_CONTAINER_SELECTION_LEFT : COFFEE_BEAN_CONTAINER_SELECTION_RIGHT,
      },
    ]
    await selectProgram(control.store._datasource.haId, activeProgramKey.value, options)
  },
})

/**
 * 清洁程序不显示调节参数和双杯
 */
const isHideAdjustBtn = computed(() => control.store.isCleaningProgram)

/**
 * 双杯
 */
const isSupportMultipleBeverages = computed(() =>
  control.store.detail?.option?.some((option) => option.key === COFFEE_MULTIPLE_BEVERAGES)
)
const isDouble = computed(() => control.store.isDouble)
const doubleDisabled = computed(() => {
  return !isSupportMultipleBeverages.value || !isPowerOn.value || !activeProgramKey.value
})
async function chooseDouble() {
  // 虚拟家电不发指令
  if (props.control.store.isVirtualAppliance) {
    control.store.isDouble = !control.store.isDouble
    return
  }
  uni.showLoading({
    title: i18n.t('APP.Common.Submitting.Text'),
    mask: true,
  })
  try {
    let options = [
      {
        key: COFFEE_MULTIPLE_BEVERAGES,
        value: !isDouble.value,
      },
    ]
    await selectProgram(control.store._datasource.haId, activeProgramKey.value, options)
    uni.hideLoading()
  } catch (error) {
    uni.hideLoading()
  }
}

/**
 * 状态显示
 */
const { pauseDisabled, abortDisabled, pauseSupported } = useControlState(control)
const customStateGetter: CustomConfigGetter = (currentState, defaultGetter) => {
  let config: StateViewConfig = defaultGetter(currentState)
  if (currentState !== OPERATION_STATES.RUN || isStartupCleaning.value) return config

  if (control.store.isCleaningProgram) {
    config.title = i18n.t('Appliance.StateView.MachineCheck.Title')
    config.contents = []
  } else {
    config.title = i18n.t('Appliance.StateView.Making.Title')
  }

  config.actions = [
    {
      name: i18n.t('Appliance.StateView.Abort.Button.Text'),
      presetEvent: 'abort-confirm',
      disabled: abortDisabled.value,
    },
  ]
  if (pauseSupported.value) {
    config.actions.unshift({
      name: i18n.t('Appliance.StateView.Pause.Button.Text'),
      presetEvent: 'pause',
      disabled: pauseDisabled.value,
    })
  }
  return config
}
</script>

<style lang="less">
.CoffeeMaker {
  :deep .program-list {
    .list-tab-bar {
      width: calc(100% - 210rpx);
      padding: 0 32rpx;
    }
  }
}
</style>

<style scoped lang="less">
// 豆仓
.bean-box {
  display: flex;
  align-items: center;
  margin-top: 32rpx;
  .bean-font {
    font-weight: 400;
    font-size: 28rpx;
    line-height: 40rpx;
    color: #000000;
    padding-right: 28rpx;
  }
  .bean-operate {
    width: 320rpx;
    height: 64rpx;
    background: rgba(118, 118, 128, 0.12);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 4rpx;
    box-sizing: border-box;
    .bean {
      width: 156rpx;
      height: 56rpx;
      line-height: 56rpx;
      font-weight: 500;
      font-size: 26rpx;
      color: #333333;
      text-align: center;
    }
    .active {
      height: 56rpx;
      background-color: #fff;
      font-weight: 600;
    }
  }
}
.disabled {
  opacity: 0.4;
  pointer-events: none;
}
.double-cup {
  display: flex;
  align-items: center;
  .double-img-box {
    width: 40rpx;
    height: 40rpx;
    image {
      width: 100%;
      height: 100%;
    }
  }
  .double-cup-font {
    width: 66rpx;
    font-weight: 500;
    font-size: 32rpx;
    line-height: 44rpx;
    color: #333333;
    margin-left: 16rpx;
    margin-right: 28rpx;
  }
}
</style>
